import { Injectable } from '@angular/core';
import { AppConfig } from "../config";
import { Http, Headers } from "@angular/http";
import { UserAlarmconfig, ForUserAlarmconfig } from "../entity/user_alarmconfig.model";
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class UserAlarmconfigService {
    private readonly param = "userAlarmConfigs";
    private get url(): string {
        return `${AppConfig.APP_RESTFUL}/${this.param}`;
    }
    constructor(private http: InterceptorService) { }
    /**
     * 获取用户报警配置集合
     * 
     * @returns {Promise<UserAlarmconfig[]>} 
     * @memberof UserAlarmconfigService
     */
    getUserAlarmconfigs(): Promise<UserAlarmconfig[]> {
        return this.http.get(this.url)
            .toPromise()
            .then(response => response.json().data as UserAlarmconfig[])
            .catch(this.handleError);
    }
    /**
     * 根据用户Id,获取用户报警配置集合
     * 
     * @returns {Promise<UserAlarmconfig[]>} 
     * @memberof UserAlarmconfigService
     */
    getUserAlarmconfigsByUserId(userId: number): Promise<UserAlarmconfig[]> {
        return this.http.get(`${this.url}/user/${userId}`)
            .toPromise()
            .then(response => response.json().data as UserAlarmconfig[])
            .catch(this.handleError);
    }
    update(forUserAlarmconfig: ForUserAlarmconfig): Promise<ForUserAlarmconfig> {
        return this.http
            .put(this.url, JSON.stringify(forUserAlarmconfig))
            .toPromise()
            .then(() => forUserAlarmconfig)
            .catch(this.handleError);
    }
    create(selectedAlarm): Promise<number> {
        return this.http
            .post(this.url, JSON.stringify(selectedAlarm))
            .toPromise()
            .then(res => res.json().code)
            .catch(this.handleError);
    }
    private handleError(error: any): Promise<any> {
        // console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}


// WEBPACK FOOTER //
// ./src/app/service/user_alarmconfig.service.ts